<template>
  <div class="ml-2 flex-1">
    <a-card :bordered="false" style="height: 820px; width: 1380px">
      <a-form :model="searchForm" ref="formRef" layout="inline">
        <a-form-item label="所属机构" name="comId">
          <a-tree-select v-model:value="searchForm.comId" tree-node-filter-prop="label" style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="comanyList" placeholder="请选择归属机构" />
        </a-form-item>
        <a-form-item label="模版类型" name="templateType">
          <a-select v-model:value="searchForm.templateType" style="width: 120px" placeholder="请选择" />
        </a-form-item>
        <a-form-item label="消息模版" name="templateId">
          <a-select v-model:value="searchForm.templateId" style="width: 120px" placeholder="请选择" />
        </a-form-item>
        <a-form-item label="发送人" name="applicantId">
          <a-select v-model:value="searchForm.applicantId" style="width: 120px" placeholder="请选择" />
        </a-form-item>
        <a-form-item label="发送时间" name="time">
          <a-range-picker v-model:value="searchForm.time" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch">
            <SearchOutlined />查询
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onExportHistory">
            <HistoryOutlined />导出历史
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onExport">
            <CloudDownloadOutlined />导出
          </a-button>
        </a-form-item>
      </a-form>
      <a-table :columns="columns" :data-source="dataSource" :pagination="pagination" row-key="id" class="mt-3">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'active'">
            <a-button type="primary">发送状况</a-button>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal :visible="isHistory" title="导出历史" :footer="null" width="1200px" @cancel="isHistory = false">
      <a-table :columns="historyColumns" :data-source="historyDataSource" bordered :pagination="historyPagination"
        class="mt-3" :row-class-name="(_record: any, index: number) =>
          index % 2 === 1 ? 'table-striped' : null
          " :scroll="{ y: 490 }">
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'states'">
            <a-tag :bordered="false" color="success" v-if="record.states == '0'">完成</a-tag>
            <a-tag :bordered="false" color="error" v-else>失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import {
  SearchOutlined,
  HistoryOutlined,
  CloudDownloadOutlined,
} from '@ant-design/icons-vue';
import {
  getHistoryPaymentApi,
  getHistoryExportPaymentApi,
  getPaymentHistory,
} from '#/api/core/charge';
import { getCompanyTree } from '#/api/core/develop';
import dayjs from 'dayjs';

const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const comanyList = ref([]);
const isHistory = ref(false);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      console.log(tree);
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};
getTableData();
const searchForm = reactive({
  comId: undefined,
  templateType: undefined,
  templateId: undefined,
  applicantId: '',
  time: '',
});
const formRef = ref();
const columns = [
  {
    title: '项目',
    dataIndex: 'project',
    key: 'project',
  },
  {
    title: '模版名称',
    dataIndex: 'villageName',
    key: 'villageName',
  },
  {
    title: '发送内容',
    dataIndex: 'userAddress',
    key: 'userAddress',
  },
  {
    title: '发送人数',
    dataIndex: 'userName',
    key: 'userName',
  },
  {
    title: '发送成功',
    dataIndex: 'heatCardNum',
    key: 'heatCardNum',
  },
  {
    title: '发送失败',
    dataIndex: 'year',
    key: 'year',
  },
  {
    title: '发送中',
    dataIndex: 'heatStatus',
    key: 'heatStatus',
  },
  {
    title: '申请人',
    dataIndex: 'arrearsAmount',
    key: 'arrearsAmount',
  },
  {
    title: '申请时间',
    dataIndex: 'valveType',
    key: 'valveType',
  },
  {
    title: '审批状态',
    dataIndex: 'price',
    key: 'price',
  },
  {
    title: '审批人',
    dataIndex: 'arrearsAmount',
    key: 'arrearsAmount',
  },
  {
    title: '审批时间',
    dataIndex: 'arrearsAmount',
    key: 'arrearsAmount',
  },
  {
    title: '审批意见',
    dataIndex: 'arrearsAmount',
    key: 'arrearsAmount',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
  },
];
const historyColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    align: 'center',
  },
  {
    title: '操作日期',
    dataIndex: 'operationDate',
    key: 'operationDate',
    align: 'center',
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'states',
    key: 'states',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
  },
];
const dataSource = ref([]);
const historyDataSource = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const historyPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    onExportHistory();
  },
});
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error("请选择左侧树结构！");
    return;
  } else {
    const query = {
      comId: searchForm.comId ?? '',
      templateType: searchForm.templateType ?? '',
      templateId: searchForm.templateId ?? '',
      applicantId: searchForm.applicantId ?? '',
      applicationTimeBegin: searchForm.time
        ? dayjs(searchForm.time[0]).format('YYYY-MM-DD')
        : '',
      applicationTimeEnd: searchForm.time
        ? dayjs(searchForm.time[1]).format('YYYY-MM-DD')
        : '',
      page: pagination.current,
      limit: pagination.pageSize,
      treeData: props.selectedNodeId,
    };
    getHistoryPaymentApi(query).then((res: any) => {
      console.log(res);
    });
  }

};
const onExport = () => {
  const query = {
    comId: searchForm.comId,
    templateType: searchForm.templateType,
    templateId: searchForm.templateId,
    applicantId: searchForm.applicantId,
    applicationTimeBegin: searchForm.time
      ? dayjs(searchForm.time[0]).format('YYYY-MM-DD HH:mm:ss')
      : '',
    applicationTimeEnd: searchForm.time
      ? dayjs(searchForm.time[1]).format('YYYY-MM-DD HH:mm:ss')
      : '',
  };
  getHistoryExportPaymentApi(query).then((res: any) => {
    console.log(res);
  });
};
const onExportHistory = () => {
  isHistory.value = true;
  getPaymentHistory(
    historyPagination.current,
    historyPagination.pageSize,
    13,
  ).then((res: any) => {
    console.log(res);
    historyDataSource.value = res.data.data.data;
    historyPagination.total = res.data.data.total;
  });
};
const onDown = (e: any) => {
  // console.log(e);
  const loading = message.loading({
    content: "下载中...",
    duration: 0,
  });

  try {
    // 下载地址拼接
    const url = e.urlAddress;

    // 使用a标签下载，避免X-Frame-Options错误
    const link = document.createElement("a");
    link.href = url;
    link.download = ""; // 触发下载而不是导航
    link.target = "_blank";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 关闭loading
    setTimeout(() => {
      loading();
    }, 1000);
  } catch (error) {
    console.error("下载出错:", error);
    message.error("下载出错，请重试");
    loading();
  }
};
</script>
<style scoped>
.ant-form-item {
  margin-bottom: 10px;
}
</style>
